package com.lagou.service;

import com.alibaba.fastjson.JSON;
import com.lagou.annotation.Autowired;
import com.lagou.annotation.Service;
import com.lagou.handler.UserServerHandler;
import com.lagou.server.ZkProxy;
import com.lagou.task.ZkTask;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.util.Timer;
import java.util.TimerTask;

@Service
public class UserServiceImpl implements UserService {

    @Override
    public String sayHello(String word) {
        System.out.println("调用成功--参数 "+word);
        return "调用成功--参数 "+word;
    }

    //hostName:ip地址  port:端口号
    public static void startServer(String ip,int port) throws Exception {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());

                    }
                });
        serverBootstrap.bind(ip,port).sync();

        //端口绑定启动之后，向zk下注册节点
        CuratorFramework client = ZkProxy.getClient();
        System.err.println("Host : ip = [" + ip + "] ,port = [" + port + "],Zookeeper connection established...");
        //创建临时节点,断开后节点会自动删除
        String nodeName = "/" + ip + ":" + port;
        NodeContentInfo nodeInfo = new NodeContentInfo(ip, port, 0L, System.nanoTime());
        String s = client.create().withMode(CreateMode.EPHEMERAL).forPath(nodeName, JSON.toJSONString(nodeInfo).getBytes());
        System.out.println("创建节点结果成功");

        System.out.println("开启定时任务");
        // 启动定时器线程，并在10000毫秒后执行TimerTask实例的run方法
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ZkTask zkTask = new ZkTask();
                zkTask.clearResponseTime();
            }
        }, 5000,5000);
    }

}
